import React from 'react'

import { sessionLocalStorage } from 'helpers/session'
import { IAction } from './types'
import { ILoginResult } from 'apis/types/auth'




export const ACTIONS = {
  LOGIN: 'LOGIN',
  LOGOUT: 'LOGOUT',
}

export interface IState {
  isLogined: boolean
  user: ILoginResult
}

const session = sessionLocalStorage.getItem()



export const initLogState = {
  isLogined: !!session.userId,
  user: session,
}
const logReducer = (state: IState, action: IAction) => {
  const { type, payload } = action
  switch (type) {
    case ACTIONS.LOGIN: {
      sessionLocalStorage.setItem(payload?.user)
      return {
        ...state,
        isLogined: true,
        user: payload?.user,
      }
    }
    case ACTIONS.LOGOUT: {
      sessionLocalStorage.removeItem()
      return {
        ...state,
        isLogined: false,
        user: {},
      }
    }
    default:
      return state
  }
}

export default logReducer
export const LoginContext = React.createContext<any>(null);

